﻿using System;
using System.Windows.Input;
using Utils.Wpf;

namespace StockAnalyst2.StockGrid
{
	internal class OptionsDialogVM : IDisposable
	{
		#region Attributes

		private readonly AllColumnsOptions _originalOptions;

		#endregion

		#region Properties

		public AllColumnsOptionsVM AllColumnsOptionsVM { get; private set; }

		public bool DataChanged
		{
			get
			{
				return !_originalOptions.Equals(this.AllColumnsOptionsVM.Model);
			}
		}

		public ICommand AcceptCommand { get; private set; }
		public ICommand CancelCommand { get; private set; }

		#endregion

		#region Events

		public event EventHandler<DialogCloseRequestedEventArgs> DialogCloseRequested;

		#endregion

		#region Public Methods

		public OptionsDialogVM(AllColumnsOptions columnsOptions)
		{
			_originalOptions = columnsOptions;
			this.AllColumnsOptionsVM = new AllColumnsOptionsVM((AllColumnsOptions)columnsOptions.Clone());

			this.AcceptCommand = new DelegateCommand(this.ExecuteAccept, this.CanExecuteAccept);
			this.CancelCommand = new DelegateCommand(this.ExecuteCancel);
		}

		protected virtual void OnDialogCloseRequested(bool? result)
		{
			if (this.DialogCloseRequested != null)
			{
				this.DialogCloseRequested(this, new DialogCloseRequestedEventArgs(result));
			}
		}

		#endregion

		#region Private Methods

		private void ExecuteAccept()
		{
			this.OnDialogCloseRequested(true);
		}

		private bool CanExecuteAccept()
		{
			return !this.AllColumnsOptionsVM.HasValidationErrors;
		}

		private void ExecuteCancel()
		{
			this.OnDialogCloseRequested(false);
		}

		#endregion

		#region IDisposable

		protected bool Disposed { get; private set; }

		private void Dispose(bool disposing)
		{
			if (!this.Disposed)
			{
				this.InternalDispose(disposing);
			}

			this.Disposed = true;
		}

		protected virtual void InternalDispose(bool disposing)
		{
			if (disposing)
			{
				this.AllColumnsOptionsVM.Dispose();
			}

			// Dispose here only unmanaged objects 
			// Don’t use managed objects here because maybe 
			// they have been finalized already
		}

		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		~OptionsDialogVM()
		{
			this.Dispose(false);
		}

		#endregion
	}
}
